var url = "";
var data1 ={//用来保存点击classify页面后保存的一列数据,保存一列的数据
  class_name:"",
  descriptions:"",
  path:""
};
var selected_class_id = null;
var status;
var list;
var option_data;//保存option选取的值
var class_name ;
var descriptions;
var has_loaded = false;//用于标记load数据是否已经加在过，加载过就不需要再次加载了。
var has_classified = false;
var GoTime,CheckTime,Time = 0;

var GLOBAL_GI = null;

$(function(){
  $(".classify-data-table table tbody tr td button").on("click",function(){
    show_modals("myModal");
  });
  $(".btn-download").on("click",function(){
    show_modals("myModal2");
  });
  $(".jianjie").css("display","block");
  $(".zyc").css("height",$(window.document).height()+"px");
  $("#user").on("click",function(){
  });
  $("#user").on("mouseout",function(){
  });
  var username = $.cookie("username");//是否登录，没有登录的话就跳转到登录界面
  if(!username){
    window.location.href = "login.html";
  }
  $(document.body).on("click",function(){
    hide_user_list();
    event.stopPropagation();
  });
  GoTime = setInterval(function(){
    if(Time <= 15*60){
      Time ++;
    }else{
      clearInterval(GoTime);
      window.location.href = "login.html";
    }
  },1000);
  $(window.document.body).click(function(){
    Time = 0;
  });
  $('#saveBatch').on('click',function(){
    if($('#batchName').val() == ''){
      $('#myModalBatch').modal("show");
    }else{
      var json = {};
      json.batchName = $('#batchName').val();
      json.description = $('#description').val();
      $.ajax({
        url: '/temp_table/save',
        type: 'post',
        dataType: 'json',
        data: json,
        cache: false,
        success:function(data){
          //alert('save success!');
          my_notice('save success!');
        },
        error:function(msg){
          //alert('connect error!');
          my_notice('connect error!');
        },
      });
    }
  });
});

function show_modals(modal_id){
  $("#"+modal_id).modal("show");
}
function show_page(page_class){
  $(".right>div").hide();
  $("."+page_class).show();
}
function change_bg_color(obj,str){
  //$(".nav-son").css("background-color","white");
  $(".nav-son").removeClass("bg-primary");
  $(obj).addClass("bg-primary");
  $(".show-container>div").css("display","none");
  $("."+str).css("display","block");
}

function show_classify_page(){
  $("#myModal").modal("hide");
  show_page("classify-data");
  set_btn_status(2);
  btn_status = 2;
  set_icon_status(2);
  open_status_window("Loading");
}
function set_radio(obj){
  if($(obj).attr("checked")){
    $(obj).attr("checked",false) ;
    $(obj).attr("value","0");
  }else {
    $(obj).attr("checked",true) ;
    $(obj).attr("value","1");
  }
}
function show_manual(obj,id){
  var a = $(obj).prev().eq(0);//a是用来保存搜索查询条件的
  $("#"+id).modal("show");
  $('#'+id).modal().css({
    width: '200px',
    'margin-left': function () {
      return -($(this).width() / 2);
    }
  });

}

function logout(){//退出登录

  $.ajax({
    url:"/user/logout",
    type:"post",
    dataType:"json",
    cache:false,
    data:"",
    success:function(data){
      if(data.result == "SUCCESS"){
        $.cookie("username",null);
        window.location.href = "login.html";
      }
    },
    error:function(msg){

    }
  });
}
function change_button_color(obj,num){//改变按钮的颜色
  //$(obj).addClass("btn-primary");
  change_button_status(num);
}
function load_data(){//点击classify按钮后开始load数据模块，预先加载load data 页面的表格数据

  if(!has_loaded){
    set_btn_status(btn_status);
    set_icon_status(1);
    btn_status = 1;
    $.ajax({
      url:"/loaddata",
      type:"get",
      dataType:"json",
      success:function(res){
        close_status_window(500);
        $("#template1").tmpl(res).appendTo("#load-table");//tmpl模板往table里面插入数据
      },
      error:function(msg){
        set_text("connecting error...");
        close_status_window(500);
      }
    });
    open_status_window("Loading...");
    has_loaded = true;
  }else{//已经ajax加载过的页面不需要再次加载
  }
}

function init_classify_page_data(){//点击模态框是否要load数据的时候，点击确定，然后开始初始化，preliminary classify页面的数据
  $("#one-table tbody tr td").eq(0).text(data1.class_name);
  $("#one-table tbody tr td").eq(1).text(data1.descriptions);

}
function save_class_name(obj){//利用data1这个json保存name，descriptsions，以及path这三个列
  data1.class_name = $(obj).prev().prev().text();
  data1.descriptions = $(obj).prev().text();
  data1.path = $(obj).prev().prev().prev().text();
  data1.id = $(obj).prev().prev().prev().prev().text();
  storeData1(data1);
  send_selected_data(data1.class_name,data1.descriptions);//
}

// 点击Load saved data按钮后也要保存选择的data的信息
function save_class_message(obj){
  data1.descriptions = $(obj).prev().prev().text();
  data1.class_name = $(obj).prev().prev().prev().text();
  data1.path = $(obj).prev().prev().prev().prev().text();
  data1.id = $(obj).prev().prev().prev().prev().prev().text();
  storeData1(data1);
}

function classify_data(){//
  var path = {
    path:data1.path
  };
  io.socket.post('/loaddata/classify', path, function (resData) {
      var status = resData.result;
      if(status === "SUCCESS") {

          close_status_window(1000);
          get_set_summary_data();
          show_page("classify-result");
          set_icon_status(3);
        set_btn_status(3);
      }else{
          $(".doing").text(JSON.stringify(resData.message));
          setTimeout(function(){
              hide_block();
          },1500);
      }
  });
    io.socket.on('/classifyPercent',function(data){
        var num = parseInt((data.percent)*100);
      set_text(num+"%");
    });
  $("#myModal-classify").modal("hide");
  open_status_window("Loading...");
  /*$.ajax({
    url:"/loaddata/classify",
    timeout:100000000,
    type:"post",
    dataType:"json",
    data:path,
    success:function(data){
      var status = data.result;
      if(status === "SUCCESS"){
        close_status_window(1000);
        get_set_summary_data();
        show_page("classify-result");
        set_btn_status(3);
        btn_status = 3;
        set_icon_status(3);

      }else{
        $(".doing").text("error！");
        setTimeout(function(){
          hide_block();
        },1500);
      }
    },
    error:function(msg){
      set_text("connecting error...");
      close_status_window(500);
    }
  });
  open_status_window("Loading...");
  $("#myModal-classify").modal("hide");*/
}

function show_hidden_block(){
  var doing  =  $(".doing");
  var zyc = $(".zyc");
  zyc.css("display","block");
  doing.css("display","block");
  var doing_width = parseInt(doing.css("width"));
  var doing_height = parseInt(doing.css("height"));
  var client_width = $(window).width();
  var client_height = $(window).height();
  var real_left = (client_width - doing_width) / 2;
  var real_top = (client_height - doing_height) / 2;
  doing.css("left",real_left+"px");
  doing.css("top",real_top+"px");
  $(document.body).css("overflow","hidden");
}
function hide_block(){
  $(".zyc").hide();
  $(".doing").hide();
  $(window.document.body).css("overflow","auto");
}

function get_set_summary_data(){
  $("#summary-table tbody").remove();//每次吧数据放在表格的时候记得提前清空
  $.ajax({
    url:"/temp_table/subclassCount",
    type:"get",
    dataType:"json",
    success:function(data){
      if(data.result === "SUCCESS"){

        close_status_window(500);
        $("#myTemplate3").tmpl(data.message).appendTo("#summary-table");//tmpl模板往table里面插入数据
      }else{
        set_text("connecting error...");
        close_status_window(500);
      }
    },
    error:function(msg){
      set_text("connecting error");
      close_status_window(1000);
    }
  });
  open_status_window("Loading...");
}
function find_data(obj,num){//obj button本身 ，num=1：代表all，num=2：代表20条数据
  var str ;
  var page_num;
  var j_data ;
  if( num == 1 ){
    str = $(obj).prev().text();
    var skip = 0;
    var limit = 1;
    find_all(str,skip,limit);
    $(obj).css("background-color","lightgrey");
    set_status(1);//保存到底是点击All还是20的状态，All为1,20为2
  }else if(num == 2){
    str = $(obj).prev().prev().text();
    find_twenty(str);
    $(obj).css("background-color","lightgrey");
    set_status(2);//保存到底是点击All还是20的状态，All为1,20为2
  }
}
function find_twenty(str){
  $.ajax({
    url:"/temp_table/getSamples?Subclass="+str,
    type:"post",
    dataType:"json",
    success:function(data){
      if(data.message.count > 0){

        close_status_window(1000);
        $("#sum-number").text(data.message.count);
        show_page("self-classify");
        list = data.message.list;
        $("#save-id").text(data.message.list[0].id);
        $("#dangqian").text(1);//设置当前页码为1
        $(".manual-title>span").text(data.message.list[0].id);
        //$(".manual-left-content").text(data.message.list[0].Infomation);//在隐藏域里面保留每一条数据的id

        GLOBAL_GI = data.message.list[0].GI;//获取GI，用来查询表格
        getProcessResultsTable(GLOBAL_GI);//ajax一部获取process results表格

        data.message.list[0].Infomation=data.message.list[0].Infomation.replace(/\n/g,"<br/>");
        data.message.list[0].Infomation=data.message.list[0].Infomation.replace(/ /g,"&nbsp;");
        document.getElementById("infomation").innerHTML = data.message.list[0].Infomation;
        $("#reason").text(data.message.list[0].Reason);
        $("#process").text(data.message.list[0].State);
        change_btn_color(3);//设置状态
      }else{
        $("#my-notice .modal-footer button").hide();
        my_notice("There are no entries.");
        setTimeout(function(){
          $("#my-notice").modal("hide");
        },1000);
        setTimeout(function(){
          $("#my-notice .modal-footer button").show();
        },2000);
        close_status_window(500);
      }
    },
    error:function(msg){
      set_text("connecting error...");
      close_status_window(1000);
    }
  });
  open_status_window("Loading...");
}
function find_all(str,skip,limit){//找到所有的数据
  $.ajax({
    url:"/temp_table/count?Subclass="+str,
    type:"get",
    dataType:"json",
    success:function(data){
      if(data.result === "SUCCESS"){
        if(data.message > 0){
          $("#sum-number").text(data.message);
          $.ajax({
            //url:"temp_table?skip="+skip+"&limit="+limit+"&Subclass="+str,
            url:"/temp_table?skip="+skip+"&limit="+limit+"&Subclass="+str+"&sort=GI ASC",
            type:"get",
            dataType:"json",
            success:function(data){
              close_status_window(1000);
              $("#Subclass").text(str);
              $("#reason").text(data[0].Reason);
              $("#process").text(data[0].State);
              $("#save-id").text(data[0].id);//在隐藏域里面保留第一条的id
              $("#dangqian").text(1);//设置当前页码为1
              $(".manual-title>span").text(data[0].id);
              show_page("self-classify");

              GLOBAL_GI = data[0].GI;//获取GI，用来查询表格
              getProcessResultsTable(GLOBAL_GI);//ajax一部获取process results表格

              //$(".manual-left-content").text(data[0].Infomation);
              data[0].Infomation=data[0].Infomation.replace(/\n/g,"<br/>");
              data[0].Infomation=data[0].Infomation.replace(/ /g,"&nbsp;");
              document.getElementById("infomation").innerHTML = data[0].Infomation;
              change_btn_color(3);//设置状态
            },
            error:function(msg){
              set_text(msg);
              close_status_window(500);
            }
          });
        }else{
          $("#my-notice .modal-footer button").hide();
          my_notice("There are no entries.");
          setTimeout(function(){
            $("#my-notice").modal("hide");
          },1000);
          setTimeout(function(){
            $("#my-notice .modal-footer button").show();
          },2000);
          close_status_window(500);
        }
        //这里可能需要在新建一个状态窗口
      }else{
        set_text("connecting error...");
        close_status_window(500);
      }
    },
    error:function(msg){
      set_text("connecting error...");
    }
  });
  open_status_window("Loading...");
}

function set_status(num){
  status = num;
}
function get_next_page(){//获取下一页
  kill_button();
  var max = parseInt($("#sum-number").text());
  var skip = parseInt($("#dangqian").text()) + 1;
  if(status == 1){
    if(skip <= max){
      //执行查询下一页的操作

      $.ajax({
        //url:"temp_table?skip="+skip+"&limit="+limit+"&Subclass="+str,
        url:"/temp_table?skip="+(skip-1)+"&limit="+1+"&Subclass="+$("#Subclass").text()+"&sort=GI ASC",
        type:"get",
        dataType:"json",
        success:function(data){
          change_number("plus");
          //$(".manual-left-content").text(data[0].Infomation);
          data[0].Infomation=data[0].Infomation.replace(/\n/g,"<br/>");
          data[0].Infomation=data[0].Infomation.replace(/ /g,"&nbsp;");
          document.getElementById("infomation").innerHTML = data[0].Infomation;

          GLOBAL_GI = data[0].GI;//获取GI，用来查询表格
          getProcessResultsTable(GLOBAL_GI);//ajax一部获取process results表格

          $("#reason").text(data[0].Reason);
          $("#process").text(data[0].State);
          $("#save-id").text(data[0].id);
          $(".manual-title>span").text(data[0].id);
          live_button();
        },
        error:function(msg){
          my_notice(msg);
          live_button();
        }
      });
    }else{
      //没有下一页
      $("#hidden_button").css("display","none");
      my_notice("No more pages !");

      setTimeout(function(){
        $("#my-notice").modal("hide");

      },1500);
      setTimeout(function(){
        $("#hidden_button").css("display","block");
      },2500);
      live_button();
    }
  }else if(status == 2){
    if(skip <= max){
      change_number("plus");
      skip--;
      //$(".manual-left-content").text(list[skip].Infomation);
      list[skip].Infomation=list[skip].Infomation.replace(/\n/g,"<br/>");
      list[skip].Infomation=list[skip].Infomation.replace(/ /g,"&nbsp;");
      document.getElementById("infomation").innerHTML = list[skip].Infomation;
      $("#reason").text(list[skip].Reason);
      $("#process").text(list[skip].State);
      $("#save-id").text(list[skip].id);
      $(".manual-title>span").text(list[skip].id);

      GLOBAL_GI = list[skip].GI;//获取GI，用来查询表格
      getProcessResultsTable(GLOBAL_GI);//ajax一部获取process results表格

      live_button();
    }else{
      $("#hidden_button").css("display","none");
      my_notice("No more pages !");

      setTimeout(function(){
        $("#my-notice").modal("hide");

      },1500);
      setTimeout(function(){
        $("#hidden_button").css("display","block");
      },2500);
      live_button();
    }
  }
}
function get_pre_page(){//获取前一页的数据
  kill_button();
  var skip = parseInt($("#dangqian").text()) - 1;
  if(status == 1){
    if(skip > 0){
      //执行查询前一页的操作
      $.ajax({
        //url:"temp_table?skip="+skip+"&limit="+limit+"&Subclass="+str,
        url:"/temp_table?skip="+(skip-1)+"&limit="+1+"&Subclass="+$("#Subclass").text()+"&sort=GI ASC",
        type:"get",
        dataType:"json",
        success:function(data){
          //$(".manual-left-content").text(data[0].Infomation);
          change_number("jian");
          data[0].Infomation=data[0].Infomation.replace(/\n/g,"<br/>");
          data[0].Infomation=data[0].Infomation.replace(/ /g,"&nbsp;");

          GLOBAL_GI = data[0].GI;//获取GI，用来查询表格
          getProcessResultsTable(GLOBAL_GI);//ajax一部获取process results表格

          document.getElementById("infomation").innerHTML = data[0].Infomation;
          $("#reason").text(data[0].Reason);
          $("#process").text(data[0].State);
          $("#save-id").text(data[0].id);
          $(".manual-title>span").text(data[0].id);
          live_button();
        },
        error:function(msg){
          my_notice(msg);
          live_button();
        }
      });
    }else{
      $("#hidden_button").css("display","none");
      my_notice("No more pages !");

      setTimeout(function(){
        $("#my-notice").modal("hide");

      },1500);
      setTimeout(function(){
        $("#hidden_button").css("display","block");
      },2500);
      live_button();
    }
  }else if(status == 2){
    if(skip > 0){
      change_number("jian");
      skip--;
      //$(".manual-left-content").text(list[skip].Infomation);
      list[skip].Infomation=list[skip].Infomation.replace(/\n/g,"<br/>");
      list[skip].Infomation=list[skip].Infomation.replace(/ /g,"&nbsp;");

      GLOBAL_GI = list[skip].GI;//获取GI，用来查询表格
      getProcessResultsTable(GLOBAL_GI);//ajax一部获取process results表格

      document.getElementById("infomation").innerHTML = list[skip].Infomation;
      $("#reason").text(list[skip].Reason);
      $("#process").text(list[skip].State);
      $("#save-id").text(list[skip].id);//隐藏域保存id
      $(".manual-title>span").text(list[skip].id);
      live_button();
    }else{
      $("#hidden_button").css("display","none");
      my_notice("No more pages !");

      setTimeout(function(){
        $("#my-notice").modal("hide");

      },1500);
      setTimeout(function(){
        $("#hidden_button").css("display","block");
      },2500);
      live_button();
    }
  }
}
function change_number(oprater){//改变分页控件的数字
  if(oprater === 'plus'){
    var num = parseInt($("#dangqian").text()) ;
    num ++;
    $("#dangqian").text(num);
  }else if(oprater === 'jian'){
    var num = parseInt($("#dangqian").text()) ;
    num -- ;
    $("#dangqian").text(num);
  }
}

function submit_modify_data(){//提交修改的数据
  var data11 = {
    id:$("#save-id").text(),
    Reason:$("#textarea-reson").val(),
    State:$("#manual-right-select").val()
  };

  $.ajax({
    url:"/Temp_table/changeState",
    type:"post",
    dataType:"json",
    data:data11,
    success:function(data){
      close_status_window(1000);
      $("#textarea-reson").val(" ");
      get_next_page();
      if(status == 2){
        refresh_data(data11.State,data11.Reason);//20 的情况下，既要刷新本地还要刷新远程
      }
    },
    error:function(msg){
      set_text("connecting error...");
      close_status_window(1000);
    }
  });
  open_status_window("Saving...");
}
function get_option_data(){//获取option的值
  return $("#manual-right-select").val();
}
function get_textarea_data(){
  return $("#textarea-reson").val();
}

function my_notice(message){//模板 消息提示
  $("#real-message").text(message);
  $("#my-notice").modal("show");

}
function kill_button(){//设置按钮不能点击
  $("#btn_prev").attr("disabled",true);
  $("#btn_next").attr("disabled",true);
  $("#my_submit").attr("disabled",true);
}
function live_button(){//回复按钮可以点击
  $("#btn_prev").attr("disabled",false);
  $("#btn_next").attr("disabled",false);
  $("#my_submit").attr("disabled",false);
}
function refresh_data(state,reason){
  list[parseInt($("#dangqian").text()-1)].State = state;
  list[parseInt($("#dangqian").text()-1)].Reason = reason;
}

function open_blast_page(){//

  $.ajax({
    url:"/Temp_table/countByState",
    type:"post",
    dataType:"json",
    data:{
      beforeBlast:true
    },
    success:function(data){
      if(data.result == "SUCCESS"){
        close_status_window(500);
        $("#blast_table1").empty();
        $("#blast_tmpl1").tmpl(data.message).appendTo("#blast_table1");//tmpl模板往table里面插入数据
      }else{
        set_text("error...");
        close_status_window(1000);
      }

    },
    error:function(msg){
      set_text("error...");
      close_status_window(1000);
    }
  });
  open_status_window("Loading...");
}

function start_blast(){//点击blast按钮后开始向后台发送blast命令
  io.socket.post('/temp_table/blast', {}, function (data) {
    if(data.result == "SUCCESS"){
      $.ajax({
        url:"/Temp_table/countByState",
        type:"post",
        dataType:"json",
        data:{},
        success:function(data){

          close_status_window(500);
          $("#blast_table2").empty();
          $(".blast-hidden").show();
          $("#blast_tmpl2").tmpl(data.message).appendTo("#blast_table2");//tmpl模板往table里面插入数据
        },
        error:function(msg){
          set_text("error...");
          close_status_window(1000);
        }
      });
    }else{
      set_text("error...");
      close_status_window(1000);
    }
  });
  open_status_window("Loading...");
}
//点击进入batch页面的时候加载一次数据
function loadBtachListData(){
  $('#batch_list_tbody').empty();
  $.ajax({
    url:"/batch",
    type:"get",
    dataType:"json",
    data:'',
    success:function(data){
      $("#batch_list").tmpl(data).appendTo("#batch_list_tbody");
    },
    error:function(msg){
      //alert(msg);
      my_notice(msg);
    },
  });
}

//获取Process results表格
function getProcessResultsTable(in_GI){
  $('#process_results_tbody').empty();
  $.ajax({
    url: '/batchResult/getInfo?GI=' + in_GI,
    type: 'get',
    dataType: 'json',
    data: '',
    success:function(data){
      if(data.result == 'SUCCESS'){
        $("#process_results_model").tmpl(data.message).appendTo("#process_results_tbody");
      }else{
        //alert('加载数据失败');
        my_notice('loading error!');
      }
    },
    error:function(msg){
      //alert(msg);
      my_notice('loading error!');
    }
  });
}

//临时保存结果
function saveTmp(){
  io.socket.post('/temp_table/save_temp', {data_id: data1.id}, function (resData) {
    var status = resData.result;
    if (status === "SUCCESS") {
      my_notice('Save success.');
      close_status_window(1000);
    } else {
      $(".doing").text(JSON.stringify(resData.message));
      setTimeout(function () {
        my_notice('Save failure.');
        hide_block();
      }, 1500);
    }
  });
  open_status_window("Loading...");
}

// 加载保存的数据
function loadSavedData(){
  io.socket.post('/loadData/selectSavedData', {data_id: data1.id}, function (resData) {
    var status = resData.result;
    if (status === "SUCCESS") {
      my_notice('Saved success.');
      close_status_window(1000);

      my_notice('Load success.');
      init_classify_page_data();
      set_btn_status(2);
      btn_status = 2;
      set_icon_status(2);

      get_set_summary_data();
      show_page("classify-result");
      set_icon_status(3);
      set_btn_status(3);
    } else {
      $(".doing").text(JSON.stringify(resData.message));
      setTimeout(function () {
        my_notice('Load failure.');
        hide_block();
      }, 1500);
    }
  });
  open_status_window("Loading...");
}

// 把data1存储到localStorage中，方便别的文件调用
function storeData1 (dd) {
  $.cookie('data1', JSON.stringify(dd));
}
